package com.server.llh.llhserverwork.activity.base;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.card.bleNfcBase.LLHBleNfcBaseActivity;
import com.lelaohui.net.BaseLeLaohuiAcitivity;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.server.llh.llhserverwork.utils.Constant;

import java.nio.ByteBuffer;

/**
 * Created by ZTF on 2017-06-01.
 */

public abstract class LlhBaseNFCActivity extends LLHBleNfcBaseActivity {
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;

    private BroadcastReceiver mReceiver;
    private LocalBroadcastManager lbm = null;

    public LocalBroadcastManager getLbm() {
        return lbm;
    }
    public void setLbm(LocalBroadcastManager lbm) {
        this.lbm = lbm;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getlayout());
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_BROADCAST);
        filter.addAction(Constant.ACTION_LOOP_INTENT);
        filter.addAction(Constant.OPEN_CONNECT);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String actionStr = intent.getStringExtra("action");
                if (actionStr.equals(Constant.ACTION_LOOP)) {

                    Intent mService = new Intent(Constant.ACTION);
                    mService.setPackage(getPackageName());
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("tagIntent", tagIntent);
                    mService.putExtras(bundle);
                    startService(mService);
                } else if (actionStr.equals(Constant.SET_OPEN_CONNECT)) {
                    Toast.makeText(getApplicationContext(),"net is null",Toast.LENGTH_LONG).show();
                }
            }
        };

        lbm = LocalBroadcastManager.getInstance(this);
        lbm.registerReceiver(mReceiver, filter);

        setNfcAdapter();
    }

    @Override
    public abstract void showProgress();
    protected abstract INetRequestManager getRequestManager() ;
    @Override
    public abstract void hideProgress();
    protected abstract int getlayout();
    protected abstract void initView();
    protected abstract  void doBasess();


    protected void setNfcAdapter() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            Intent flag = new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            flag.setPackage(getApplicationContext().getPackageName());
            mPendingIntent = PendingIntent.getActivity(this, 0, flag, 0);
            IntentFilter ndef = new IntentFilter(
                    NfcAdapter.ACTION_NDEF_DISCOVERED);
            try {
                ndef.addDataType("*/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                throw new RuntimeException("fail", e);
            }
            mFilters = new IntentFilter[] { ndef };
            mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (mNfcAdapter == null) {
//            ToastTool.showText(getApplicationContext(), "请检查nfc是否打开,谢谢");
                return;
            }
            if (mNfcAdapter != null)
                mNfcAdapter.enableForegroundDispatch(this, mPendingIntent,
                        mFilters, mTechLists);
            Intent intent = getIntent();
            if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
                processTag(intent);
            }
        }catch (Exception e){

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processTag(intent);
    }

    Tag tagIntent;

    public void processTag(Intent intent) {

        tagIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        if (tagIntent == null)
            return;

        setCartId(tagIntent);
    }

    protected void setCartId(Tag tagIntent) {
        long cardId = 0;
        byte[] cardUid = tagIntent.getId();
//		if (cardUid.length < 8) {
//			byte cardInt[] = byteMerger(add, byteChack(cardUid));
//			cardId = Long.parseLong(
//					Long.toHexString(setByteChackBf(cardInt).getLong()), 16);
//		} else {
//			byte cardInt[] = byteMerger(add, byteChack(cardUid));
//			cardId = Long.parseLong(Long.toHexString(setByteChackBf(
//					byteChack(cardInt)).getLong()), 16);
//		}
//		int accum = 0;
//		for (int shiftBy = 0; shiftBy < 4; shiftBy++) {
//			cardId |= (cardUid[shiftBy] & 0xff) << shiftBy * 8;
//		}



        if (cardUid.length < 8) {
            byte cardInt[] = byteMerger(add, byteChack(cardUid));
//			byteSySo(byteChack(cardInt));
            cardId=	Long.parseLong(Long.toHexString(setByteChackBf(cardInt).getLong()), 16);
        } else {
//			byteSySo(byteChack(cardUid));
            byte cardInt[] = byteMerger(add, byteChack(cardUid));
            cardId=Long.parseLong(Long.toHexString(setByteChackBf(byteChack(cardInt)).getLong()), 16);
        }
        Intent intentdata = new Intent();
        intentdata.putExtra("packname", "com.lelaohui.activity");
        intentdata.setAction("com.lelaohui.llhreadcardlib.getCardId");
        if ((new Long(cardId)).toString().length()<10){
            intentdata.putExtra("cardId", "0"+cardId + "");
        }else{
            intentdata.putExtra("cardId", cardId + "");
        }
        getLocalBroadcastManager().sendBroadcast(intentdata);
    }

    private ByteBuffer setByteChackBf(byte[] cardUid) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put(cardUid, 0, cardUid.length);
        buffer.flip();
        return buffer;
    }

    byte add[] = { 0, 0, 0, 0 };

    // 数组倒序排序
    public static byte[] byteChack(byte[] arr) {
        byte t;
        int j = arr.length;
        for (int i = 0; i < j; i++) {
            if (j >= i) {
                t = arr[i];
                arr[i] = arr[--j];
                arr[j] = t;
            } else {
                break;
            }
        }
        return arr;
    }

    // 倒序输出内容
    public static void byteSySo(byte[] a) {
        int i = a.length - 1;
        while (i >= 0) {
            System.out.println(a[i]);
            i--;
        }
    }

    // 两个数组结合
    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
        byte[] byte_3 = new byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
    }
}
